﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Zwms.Client.CommonUI;
using Zwms.Data.BusinessObjects;
using Zwms.Data.CommonObject;
using Zwms.Client.InfoSys;

//每种货物在每个库位上对应一条记录
namespace Zwms.Client.InWms
{
    public partial class AssignLocationForm : BaseForm
    {
        #region 成员变量
        BilInBill _inBill = null;
        IList<BilInBillDetail> _inBillDetailList = null;
        IList<StoGoodsStock> _stoGoodsStockList = null;
        #endregion

        #region 构造函数
        public AssignLocationForm(BilInBill inBill)
        {
            InitializeComponent();
            _inBill = inBill;
            _stoGoodsStockList = new List<StoGoodsStock>();
            InitBtnImage();
            InitControl();
        }
        #endregion

        #region 私有函数
        private void InitBtnImage()
        {
            this.btnConfirm.Image = global::Zwms.Client.Properties.Resources.ok;
            this.btnDefault.Image = global::Zwms.Client.Properties.Resources.list;
            this.btnReset.Image = global::Zwms.Client.Properties.Resources.refresh;
            this.btnPrint.Image = global::Zwms.Client.Properties.Resources.print;
            this.btnCancel.Image = global::Zwms.Client.Properties.Resources.cancel2;
        }

        private void InitControl()
        {
            _inBillDetailList = new List<BilInBillDetail>();
            _stoGoodsStockList = new List<StoGoodsStock>();
            ServiceReferenceZwms.ServiceZwmsClient client = new ServiceReferenceZwms.ServiceZwmsClient();
            BilInBillDetail queryRecord = new BilInBillDetail();
            queryRecord.IBCode = _inBill.Id;
            PagerIndex pagerIndex = new PagerIndex(1, int.MaxValue);
            _inBillDetailList = client.QueryInBillDetailList(queryRecord, ref pagerIndex);
            LoadInBillDetailList();
            LoadStockLocation();
        }

        //载入待分配货物列表
        private void LoadInBillDetailList()
        {
            dgvInBillDetailList.DataSource = null;
            if (_inBillDetailList.Count > 0)
            {
                dgvInBillDetailList.DataSource = _inBillDetailList;
            }
        }

        //载入已分配货物列表
        private void LoadStockLocation()
        {
            dgvGoodsStock.DataSource = null;
            if (_stoGoodsStockList.Count > 0)
            {
                dgvGoodsStock.DataSource = _stoGoodsStockList;
            }
        }
        #endregion

        #region 控件函数
        private void dgvInBillDetailList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (dgvInBillDetailList.CurrentCell == null)
            {
                return;
            }
            int rowIndex = dgvInBillDetailList.CurrentCell.RowIndex;

            if (rowIndex < 0)
            {
                MessageBox.Show("请首先在列表中选中项！");
                return;
            }
            DataGridViewRow row = dgvInBillDetailList.Rows[rowIndex];
            BilInBillDetail selectedRecord = row.DataBoundItem as BilInBillDetail;

            AssignLocationDetailForm window = new AssignLocationDetailForm(_inBill, selectedRecord);
            if (window.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                StoGoodsStock storecord = window.GoodsStock;
                //首先遍历goodslist，看是否已存在该项，如果是，则将其数量加入
                //存在的条件是：1 货物代码一致
                //              2 库位一致
                bool bHave = false;
                for (int i = 0; i < _stoGoodsStockList.Count; i++)
                {
                    StoGoodsStock record = _stoGoodsStockList[i];
                    if (storecord.GoodsCode == record.GoodsCode && 
                        storecord.LocationCode == record.LocationCode)
                    {
                        bHave = true;
                        record.PackageQty += storecord.PackageQty;
                        record.PieceQty += storecord.PieceQty;
                        record.GoodsTotalQty += storecord.PackageQty * storecord.GoodsSpec + storecord.PieceQty;
                        break;
                    }
                }

                if (!bHave)
                {
                    _stoGoodsStockList.Add(window.GoodsStock);
                }

                //将未分配货物中减去该货物
                if (window.InBillDetail.GoodsPackageQty == 0
                    && window.InBillDetail.GoodsPieceQty == 0)
                {
                    for (int i = 0; i < _inBillDetailList.Count; i++)
                    {
                        BilInBillDetail record = _inBillDetailList[i];
                        if (record.GoodsCode == window.InBillDetail.GoodsCode)
                        {
                            _inBillDetailList.RemoveAt(i);
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < _inBillDetailList.Count; i++)
                    {
                        BilInBillDetail record = _inBillDetailList[i];
                        if (record.GoodsCode == window.InBillDetail.GoodsCode)
                        {
                            record.ReceiveGoodsPackageQty = window.InBillDetail.ReceiveGoodsPackageQty;
                            record.ReceiveGoodsPieceQty = window.InBillDetail.ReceiveGoodsPieceQty;
                            record.ReceiveGoodsQty = window.InBillDetail.ReceiveGoodsQty;
                        }
                    }
                }

                LoadInBillDetailList();
                LoadStockLocation();
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            InitControl();
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            //确认库位分配  
            if (MessageBox.Show("确认该库存分配吗？", "提示", MessageBoxButtons.OKCancel)
              != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }
            //1.将库存信息保存到库存表中
            ServiceReferenceZwms.ServiceZwmsClient client = new ServiceReferenceZwms.ServiceZwmsClient();
             bool bSuccess = true;
            foreach (StoGoodsStock record in _stoGoodsStockList)
            {
                record.Id = client.InitGoodsStockCode();
            }
            if (client.AddGoodsStockList(_stoGoodsStockList.ToArray()))
            {
                SysLogWriter.WriteOptLog("库存列表", _inBill.Id, "增");
                //2更新入库单的状态
                _inBill.BillStatus = "2"; //正在上架
                ServiceReferenceZwms.ServiceZwmsClient client1 = new ServiceReferenceZwms.ServiceZwmsClient();
                if (client1.UpdateInBill(_inBill))
                {
                    SysLogWriter.WriteOptLog("入库单", _inBill.Id, "改");
                    MessageBox.Show("分配完成！");
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    this.Close();
                }
            }
            else
            {
                MessageBox.Show("分配失败！");
                return;
            }
        }

        private void btnDefault_Click(object sender, EventArgs e)
        {
            InitControl();
            //分配到默认库位
            //首先获取待分配库位的默认库位
            string sTip = "货物";
            int iCount = 0;
            for(int i=0;i<_inBillDetailList.Count;i++)
            {
                 BilInBillDetail record = _inBillDetailList[i];
                 if (record.ReceiveGoodsPackageQty == 0 &&
                     record.ReceiveGoodsPieceQty == 0)
                 {
                     continue;
                 }
                //获取货物的默认库位
                ServiceReferenceZwms.ServiceZwmsClient client = new ServiceReferenceZwms.ServiceZwmsClient();
               
                WhLocation queryRecord = new WhLocation();
                queryRecord.StoreGoodsCode = record.GoodsCode;
                if (_inBill.IBType.Trim() == "1")
                {
                    queryRecord.WarehouseCode = _inBill.WarehouseCode;
                }
                else
                {
                    queryRecord.WarehouseCode = MainForm.CurrentUser.WarehouseCode;
                }
                
                PagerIndex pIndex = new PagerIndex(1, int.MaxValue);
                WhLocation defaultLocation = client.QueryLocationList(queryRecord, ref pIndex).FirstOrDefault();
                if (defaultLocation != null)
                {
                    StoGoodsStock goodsStock = new StoGoodsStock();

                    //分配后的库存信息
                    //库位信息

                    goodsStock.WarehouseCode = defaultLocation.WarehouseCode;
                    goodsStock.WarehouseName = defaultLocation.WarehouseName;
                    goodsStock.AreaCode = defaultLocation.AreaCode;
                    goodsStock.AreaName = defaultLocation.AreaName;
                    goodsStock.ShelfCode = defaultLocation.ShelfCode;
                    goodsStock.ShelfName = defaultLocation.ShelfName;
                    goodsStock.LocationCode = defaultLocation.LocationCode;
                    goodsStock.LocationName = defaultLocation.LocationName;
                    //货物信息
                    goodsStock.GoodsCode = record.GoodsCode;
                    goodsStock.GoodsBarCode = record.GoodsBarCode;
                    goodsStock.SingleGoodsCode = record.SingleGoodsCode;
                    goodsStock.GoodsName = record.GoodsName;
                    goodsStock.GoodsSpec = record.GoodsSpec;
                    goodsStock.CostPrice = record.PiecePrice;
                    goodsStock.GoodsUnit = "";
                    goodsStock.PackageQty = record.ReceiveGoodsPackageQty;
                    goodsStock.PieceQty = record.ReceiveGoodsPieceQty;
                    goodsStock.GoodsTotalQty = record.ReceiveGoodsQty;

                    goodsStock.GoodsStatus = "0";//0 完好  1 破损
                    //入库单信息
                    goodsStock.IBCode = _inBill.Id;
                    goodsStock.IBDate = _inBill.ReceiveDate;
                    goodsStock.IBPlanCode = _inBill.IBPlanCode;

                    BaseGood goodsqueryRecord = new BaseGood();
                    goodsqueryRecord.Id = goodsStock.GoodsCode;
                    goodsqueryRecord = client.QueryGoods(goodsqueryRecord);
                    if (queryRecord != null)
                    {
                        goodsStock.CategoryCode = goodsqueryRecord.CategoryCode;
                        goodsStock.CategoryName = goodsqueryRecord.CategoryName;
                    }
                    //入库单中的货物数信息
                    record.ReceiveGoodsPackageQty = 0;
                    record.ReceiveGoodsPieceQty = 0;
                    record.ReceiveGoodsQty = 0;
                    _stoGoodsStockList.Add(goodsStock);
                }
                else
                {
                    iCount++;
                    sTip += string.Format("{0}.{1}\r\n", iCount, record.GoodsName);
                    StoGoodsStock goodsStock = new StoGoodsStock();

                    //分配后的库存信息
                    //库位信息
                    goodsStock.WarehouseCode = _inBill.WarehouseCode;
                    goodsStock.WarehouseName = _inBill.WarehouseName;
                    goodsStock.AreaCode = "";
                    goodsStock.AreaName = "";
                    goodsStock.ShelfCode = "";
                    goodsStock.ShelfName = "";
                    goodsStock.LocationCode = "temp";
                    goodsStock.LocationName = "临时缓存区";
                    //货物信息
                    goodsStock.GoodsCode = record.GoodsCode;
                    goodsStock.GoodsBarCode = record.GoodsBarCode;
                    goodsStock.SingleGoodsCode = record.SingleGoodsCode;
                    goodsStock.GoodsName = record.GoodsName;
                    goodsStock.GoodsSpec = record.GoodsSpec;
                    goodsStock.CostPrice = record.PiecePrice;
                    goodsStock.GoodsUnit = "";
                    goodsStock.PackageQty = record.ReceiveGoodsPackageQty;
                    goodsStock.PieceQty = record.ReceiveGoodsPieceQty;
                    goodsStock.GoodsTotalQty = record.ReceiveGoodsQty;

                    goodsStock.GoodsStatus = "0";//0 完好  1 破损
                    //入库单信息
                    goodsStock.IBCode = _inBill.Id;
                    goodsStock.IBDate = _inBill.ReceiveDate;
                    goodsStock.IBPlanCode = _inBill.IBPlanCode;

                    BaseGood goodsqueryRecord = new BaseGood();
                    goodsqueryRecord.Id = goodsStock.GoodsCode;
                    goodsqueryRecord = client.QueryGoods(goodsqueryRecord);
                    if (queryRecord != null)
                    {
                        goodsStock.CategoryCode = goodsqueryRecord.CategoryCode;
                        goodsStock.CategoryName = goodsqueryRecord.CategoryName;
                    }
                    //入库单中的货物数信息
                    record.ReceiveGoodsPackageQty = 0;
                    record.ReceiveGoodsPieceQty = 0;
                    record.ReceiveGoodsQty = 0;
                    _stoGoodsStockList.Add(goodsStock);
                }
            }

            if (iCount > 0)
            {
                MessageBox.Show(string.Format("货物：{0}无法找到默认库位，分配到临时缓存区！",sTip));
            }

            LoadInBillDetailList();
            LoadStockLocation();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            Report.ReportHelper.PrintLocationArrange(_stoGoodsStockList.ToList());
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }
        #endregion

     
    }
}
